#!/bin/sh
#
# autostart -- start stopped labs during boot
#
# TODO: need to update for "update-rc.d cloud-lab defaults 100"
#

uname | grep -q MINGW && PWD_OPT="-W"
TOP_DIR="$(cd "$(dirname "$0")"/../../ && pwd $PWD_OPT)"
. "$TOP_DIR"/tools/docker/config $* >/dev/null

[ "x$HOST_OS" != "xLinux" ] && echo "LOG: Only available for Linux currently." && exit 1

RC=/etc/rc.local
#DST=/etc/init.d/cloud-lab
LOG=/var/log/cloud-lab.autostart.log
DST=/usr/local/bin/cloud-lab-autostart
SRC="$DOCKER_START_ALL_CMD"
RELEASE="$DOCKER_RELEASE_CMD"

[ `id -u` -ne 0 ] && SUDO=sudo

echo "LOG: Install $SRC to $DST"

$SUDO rm -rf "$DST"
tmp=`mktemp`
$SUDO cat <<EOF > "$tmp"
#!/bin/sh
#
# cloud-lab -- start all of the stopped labs during boot
#
echo
echo "LOG: START @ \`date\`"
echo "LOG: Start docker service"
service docker start
echo "LOG: Start all of the stopped labs"
"$SRC"
echo "LOG: Generate release page for labs"
"$RELEASE" all
echo "LOG: END @ \`date\`"
echo
EOF

$SUDO mv "$tmp" "$DST"
$SUDO chmod a+x "$DST"
$SUDO touch "$LOG"
$SUDO chmod o-r "$LOG"

echo "LOG: Put $DST in $RC for autostart"
#$SUDO update-rc.d cloud-lab defaults 100
$SUDO sed -i -e "/cloud-lab/d" $RC
$SUDO sh -c "sed -i -e \"/^exit 0$/i$DST > $LOG\" $RC"
